package com.autonavi.yunda.yunji.core.engine.handler;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.utils.SpringUtil;
import com.autonavi.yunda.yunji.core.service.dbfactory.RedisFactoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * redis的groovy脚本执行
 */
@Slf4j
public class RedisHandler {

    /**
     * 执行groovy的内容
     *
     * @param redisInstance redis实例
     * @param operate       操作命令
     * @param key           key
     * @param value         value
     * @return 执行命令后的返回结果
     */
    public static Object redis(String redisInstance, String operate, String key, String value, String expire) {
        log.info("redisInstance : {},operate : {},key : {},value : {}", redisInstance, operate, key, value);

        RedisTemplate<Object, Object> template;
        RedisFactoryService service = SpringUtil.getBean(RedisFactoryService.class);
        try {
            template = service.getInstance(redisInstance);
        } catch (Exception e) {
            log.error("从dbFactoryService获取数据源失败 redisInstance:{}", redisInstance);
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "获取数据源失败", e);
        }
        switch (operate) {
            case "set":
                return set(template, key, value, expire);
            case "get":
                return get(template, key);
            default:
                throw new AmapException(AmapExceptionCode.COMMON_ILLEGAL_PARAM, "not support redis operate :" + operate);
        }
    }

    public static Object set(RedisTemplate<Object, Object> template, String key, String val, String expire) {
        try {
            int expireTime = Integer.parseInt(expire);
            if (expireTime > 0) {
                template.opsForValue().set(key, val, expireTime, TimeUnit.SECONDS);
            } else {
                template.opsForValue().set(key, val);
            }
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            return e;
        }
    }

    public static Object get(RedisTemplate<Object, Object> template, String key) {
        return key == null ? null : template.opsForValue().get(key);
    }
}
